package com.javaweb.dao.impl;

import com.javaweb.dao.CategoryDao;
import com.javaweb.model.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @desc:
 * @author: Ping
 * @date: 2024/10/19 16:55
 */

@Repository
public class CategoryDaoImpl implements CategoryDao {
    @Autowired
    private JdbcTemplate jdbcTemplate ;

    private RowMapper<Category > categoryRowMapper = new RowMapper<Category>() {
        @Override
        public Category mapRow(ResultSet rs, int rowNum) throws SQLException {
            Category category = new Category()
                    .setId(rs.getInt("id"))
                    .setName(rs.getString("name"))
                    .setOrder(rs.getInt("order"))
                    .setParentId(rs.getInt("parent_id"))
                    .setCreateTime(rs.getTime("create_time"))
                    .setUpdateTime(rs.getTime("update_time"));
            return category;
        }
    };


    @Override
    public int insert(Category category) {

        String sql = "INSERT INTO" +
                " tb_category (name, order, parent_Id, " +
                "create_time, update_time) VALUES (?, ?,?,?,?)" ;
        Object [] args = new Object[]{
                category.getName(),
                category.getOrder(),
                category.getParentId(),
                // java util Date   ->   java sql Date
                new Date(category.getCreateTime().getTime()),
                new Date(category.getUpdateTime().getTime())
        } ;
        return jdbcTemplate.update(sql, args);
    }

    @Override
    public Category select(int categoryId) {
        String  sql = "SELECT * FROM tb_category WHERE id = ?" ;
        Object [] args = new Object[]{categoryId} ;
        return jdbcTemplate.queryForObject(sql, args, categoryRowMapper) ;
    }
}
